package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Mycomment;

import ejb.CommentInspectRemote;
import ejb.UserFacadeEJBRemote;

/**
 * Servlet implementation class Editor
 */
@WebServlet("/Editor")
public class Editor extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	@EJB CommentInspectRemote ci;
	@EJB UserFacadeEJBRemote uf;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Editor() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("username");
				
		try{
			if(username==null){
	            out.print("Please login first! redirecting to Login...");
	            response.setHeader("Refresh","2;URL=login.jsp");
			}
			else if(!uf.findUserByName(username).getAuthority().equals("editor")){
	            out.print("Oops, seems you do not have the authority to visit the editor page. Redirecting to Home page...");
	            response.setHeader("Refresh","2;URL=home.jsp");
			}
			else {
				List<Mycomment> commentList = ci.getAllComments();			
		        request.setAttribute("comment_num", Integer.toString(commentList.size()));
		        request.setAttribute("comments", commentList);
		        request.getRequestDispatcher("editor.jsp").forward(request, response);
			}
			        			
		} catch (Exception e) {
			e.printStackTrace();				
	}
}

}
